using System;
using System.Collections.Generic;
using System.Text;

namespace RideMe.CommandManagement
{
    public class Command
    {
        public event EventHandler Update;
        public event EventHandler Execute;

        private CommandInstanceCollection _commandInstances;
        private CommandManager _manager;

        public Command(string tag, EventHandler handlerExecute, EventHandler handlerUpdate)
        {
            _commandInstances = new CommandInstanceCollection(this);
            this._tag = tag;
            Update += handlerUpdate;
            Execute += handlerExecute;
        }

        public CommandInstanceCollection CommandInstances
        {
            get
            {
                return _commandInstances;
            }
        }

        private string _tag;

        public string Tag
        {
            get { return _tag; }
        }

        internal CommandManager Manager
        {
            get
            {
                return _manager;
            }
            set
            {
                _manager = value;
            }
        }

        public override string ToString()
        {
            return Tag;
        }

        protected virtual void OnExecute(EventArgs e)
        {
            if (Execute != null)
            {
                Execute(this, e);
            }
        }

        protected virtual void OnUpdate(EventArgs e)
        {
            if (Update != null)
            {
                Update(this, e);
            }
        }

        private bool _enabled;

        public bool Enabled
        {
            get
            {
                return _enabled;
            }
            set
            {
                _enabled = value;
                foreach (object instance in _commandInstances)
                {
                    Manager.GetCommandExecutor(instance).Enable(
                        instance, _enabled);
                }
            }
        }

        private bool _checked;

        public bool Checked
        {
            get
            {
                return _checked;
            }
            set
            {
                _checked = value;
                foreach (object instance in _commandInstances)
                {
                    Manager.GetCommandExecutor(instance).Check(instance, _checked);
                }
            }
        }

        public void DoExecute()
        {
            OnExecute(EventArgs.Empty);
        }

        public void DoUpdate()
        {
            OnUpdate(EventArgs.Empty);
        }
    }
}
